

public class MySingList  {
    // 1、无头单向非循环链表实现
        //头插法
    public  static class ListNode {
        int val;
        ListNode next;
        public ListNode(int val) {
            this.val = val;
        }
    }
    ListNode head;
        public void addFirst(int data){
            ListNode node=new ListNode(data);

            node.next=head;
            head=node;
        }
        public void addLast(int data){
            ListNode node=new ListNode(data);
            if(head==null){
                head=node;
                return;
            }
            ListNode cur=head;
            while(cur.next!=null){
                cur=cur.next;
            }
            cur.next=node;
        }
        public boolean contains(int key){
            ListNode node=head;
            ListNode cur=head;
            if(head==null){
                return  false;
            }
            while(cur!=null){
                if(cur.val==key){
                    return true;
                }
                cur=cur.next;
            }
            return false;
        }
        //删除第一次出现关键字为key的节点
        public void remove(int key){
          if(head==null){
              return;
          }
          if(head.val==key){
              head=head.next;
          }
          ListNode cur=findNodeofKey(key);
          if(cur==null){
              return;
          }
          ListNode del=cur.next;
          cur.next=del.next;
        }
        //删除所有值为key的节点
    public ListNode findNodeofKey(int key) {
            ListNode cur=head;
            while(cur!=null){
                if(cur.next.val==key){
                    return cur;
                }
                cur=cur.next;
            }
            return null;
    }
        public void removeAllKey(int key){
          if(head==null){
              return;
          }
          ListNode prev=head;
          ListNode cur=head.next;
          while(cur!=null){
              if(cur.val==key){
                  prev.next=cur.next;
                  cur=cur.next;
              }else {
                  prev=cur;
                  cur=cur.next;
              }
          }
          if(head.val==key){
              head=head.next;
          }
        }
        //得到单链表的长度
        public int size(){
            int uS=0;
            ListNode cur=head;
            while(cur!=null){
                cur=cur.next;
                uS++;
            }
            return uS;
        }
        public void clear() {
            ListNode cur=head;
            while(cur!=null){
                head=cur.next;
                cur.next=null;
                cur=head;
            }
        }
        public void display() {
            ListNode cur=head;
            while(cur!=null){
                System.out.print(cur.val+" ");
                cur=cur.next;
            }
            System.out.println( );
        }
}
